package com.hanhanxiaochong.zhongxiangchuanmei.widget.webview;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Yecal on 2017/5/3.
 */

public class WebActivity extends AppCompatActivity {
    private WebView webView;
    private String url, title, html;
    private ProgressBar pg1;
    private TextView tv_tltle;

    private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调
    private Uri imageUri;
    private String dataJson;
    private AlertDialog dialog;
    private ImageView ivCommitAfter;

    public static Intent createIntent(Context context, String title, String url, String html) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        intent.putExtra("html", html);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_activity);
        findViewById(R.id.titlebar_backward).setOnClickListener(v -> finish());
        Intent intent = getIntent();
        url = intent.getStringExtra("url");
        html = intent.getStringExtra("html");
        try {
            title = intent.getStringExtra("title");
        } catch (Exception e) {
            title = "";
        }
        initView();
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void initView() {
        pg1 = findViewById(R.id.webactivity_progressBar);
        webView = findViewById(R.id.webactivity_webview);
        tv_tltle = findViewById(R.id.webactivity_title);
        ivCommitAfter = findViewById(R.id.iv_commit_after);
        if (TextUtils.isEmpty(title)) {
            tv_tltle.setText("详情");
        } else {
            tv_tltle.setText(title);
        }
        WebSettings seting = webView.getSettings();
        seting.setAllowFileAccess(true);//设置可以访问文件
        seting.setJavaScriptEnabled(true);//设置webview支持javascript脚本
        //提高渲染的优先级
        seting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        seting.setCacheMode(WebSettings.LOAD_NO_CACHE); //默认不使用缓存
        seting.setDefaultTextEncodingName("utf-8");
        webView.setWebChromeClient(new MyWebChromeClient() {
            /**
             * 覆盖默认的window.alert展示界面，避免title里显示为“：来自file:////”
             */
//            public boolean onJsAlert(WebView view, String url, String message,
//                                     JsResult result) {
//                final AlertDialog.Builder builder = new AlertDialog.Builder(
//                        WebActivity.this);
//
//                builder.setTitle("提示：").setMessage(message)
//                        .setPositiveButton("确定", null);
//
//                // 不需要绑定按键事件
//                // 屏蔽keycode等于84之类的按键
//                builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
//                    public boolean onKey(DialogInterface dialog, int keyCode,
//                                         KeyEvent event) {
//                        Log.v("onJsAlert", "keyCode==" + keyCode + "event=" + event);
//                        return true;
//                    }
//                });
//                // 禁止响应按back键的事件
//                builder.setCancelable(false);
//                dialog = builder.create();
//                dialog.show();
////                result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
//                return true;
////                 return super.onJsAlert(view, url, message, result);
//            }
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                if (newProgress == 100) {
                    pg1.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    pg1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    pg1.setProgress(newProgress);//设置进度值
                }
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                take();
                return true;
            }

            //<3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                take();
            }

            //>3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                take();
            }

            //>4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                take();
            }
        });

//        webView.addJavascriptInterface(getHtmlObject(), "jsObj");
        webView.addJavascriptInterface(new JsInteration(), "android");
        //listview,webview中滚动拖动到顶部或者底部时的阴影
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        if (url != null) {
            webView.loadUrl(url);
        } else if (html != null) {
            webView.loadData(html, "text/html; charset=UTF-8", null);//这种写法可以正确解码
        }
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }

    //设置回退
    //覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法

    //设置返回键动作（防止按返回键直接退出程序)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO 自动生成的方法存根
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            if (webView.canGoBack()) {//当webview不是处于第一页面时，返回上一个页面
                webView.goBack();
                return true;
            } else {//当webview处于第一页面时,直接退出程序
                System.exit(0);
            }


        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                Log.e("result", result + "");
                if (result == null) {
                    mUploadMessage.onReceiveValue(imageUri);
                    mUploadMessage = null;
                    Log.e("imageUri", imageUri + "");
                } else {
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }
            }
        }
    }

    public class JsInteration {

        @JavascriptInterface
        public void createBalanceOrders(String data) {
            if (data.equals("1")) {
                runOnUiThread(() -> {
                    ivCommitAfter.setImageResource(R.drawable.commit_success);
                    ivCommitAfter.setVisibility(View.VISIBLE);
                    ivCommitAfter.setOnClickListener(v -> {
                        finish();
                    });
                });
            } else {
                ToastUtils.showToast("提交失败");
            }
        }

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE || mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        if (results != null) {
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        } else {
            results = new Uri[]{imageUri};
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }
        return;
    }

    private Object getHtmlObject() {
        Object insertObj = new Object() {

            @JavascriptInterface
            public void transmits(final String transmit, final String jsonParams) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String urlParam = "";
                        Log.i("获取到的交互参数为：", jsonParams);
                        try {
                            JSONObject jb = new JSONObject(jsonParams);
                            Log.i("web取到的值为：", jsonParams);
                            urlParam = jb.getString("urlParam");
                            if (!urlParam.isEmpty()) {
                            } else {
                                ToastUtils.showToast("网络连接异常，请重新加载。。。");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        };
        return insertObj;
    }

    private void take() {
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
        if (!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }
        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        imageUri = Uri.fromFile(file);
        final List<Intent> cameraIntents = new ArrayList<Intent>();
        final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent i = new Intent(captureIntent);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            i.setPackage(packageName);
            i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            cameraIntents.add(i);
        }
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {//此方法在ui线程运行
            switch (msg.what) {
                case 0x01:
                    Log.i("WebActivity", "服务器数据请求成功！");
                    break;
                case 0x03:
                    ToastUtils.showToast("网络异常，请检查您的网络。。。");
                    break;
                case 0x05:
                    break;
            }
        }
    };
}

